package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstans;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsMaterialService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author 10161
 */
@Service
@Transactional
@Slf4j
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialService wmNewsMaterialService;

    @Autowired
    private WmMaterialService wmMaterialService;

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    /**
     * 查询文章列表信息的业务实现
     * 会涉及到多种条件查询和分页显示
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult getList(WmNewsPageReqDto dto) {
        //1.对前端传来的分页查询数据做预见性判断，判断page和size是否为空
        if (dto.getPage() == null || dto.getSize() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2.动态设置查询条件完成分页查询
        IPage iPage = new Page(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();

        //2.1 传来了channel信息与否
        wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());

        //2.2 传来了日期信息与否
        wrapper.ge(dto.getBeginPubDate() != null, WmNews::getPublishTime, dto.getBeginPubDate());
        wrapper.lt(dto.getEndPubDate() != null, WmNews::getPublishTime, dto.getEndPubDate());

        //2.3 传来了文章状态与否
        wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());

        //2.4 是否进行模糊查询
        wrapper.like(dto.getKeyword() != null, WmNews::getTitle, dto.getKeyword());

        //3.对从数据查询到的结果进行预见性判断，判断是否为空
        IPage newsPages = page(iPage, wrapper);
        if (newsPages.getRecords().isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //4.将数据封装好返回给前端

        ResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(), (int) newsPages.getTotal());
        responseResult.setData(newsPages.getRecords());
        return responseResult;
    }

    /**
     * 文章提交的业务实现
     * 会涉及到文章的修改或者新增的提交
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) {
        //1.对dto进行预见性判断
        if (dto == null || dto.getContent() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.从dto中进行参数拷贝和参数补全
        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        wmNews.setEnable((short) 1);
        //在这里写死用户了
        wmNews.setUserId(1102);
        //将封面图片的list变成string封装到这个wmnews对象中
        if (dto.getImages() != null && dto.getImages().size() > 0) {
            String imageStr = StringUtils.join(dto.getImages(), ",");
            wmNews.setImages(imageStr);
        }

        if (dto.getType().equals(WemediaConstans.WM_NEWS_TYPE_AUTO)) {
            //自动选封面，在这里设置为null，则为自动选封面的判断条件
            wmNews.setType(null);
        }

        //3.不论是草稿还是不是草稿，都会在数据进行持久化
        insertOrUpdateNews(wmNews, dto);

        //4.下面是对文章和素材的关系绑定，是草稿就不需要绑定
        if (dto.getStatus().equals((short) 0)) {
            //是草稿，直接返回
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        // 获取dto中content中的image的url，并将其关系保存到数据库中
        List<String> contentImages = ectractUrlInfo(dto.getContent());
        saveRelativeInfoForContent(contentImages, wmNews.getId());

        //保存文章和封面的绑定关系
        saveRelativeInfoForCover(dto, contentImages, wmNews);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }


    /**
     * 文章的新增或者修改的持久化操作
     *
     * @param wmNews
     * @param dto
     */
    private void insertOrUpdateNews(WmNews wmNews, WmNewsDto dto) {
        Integer id = dto.getId();
        //1.先判断是新增还是修改
        if (id != null) {
            //修改操作：1.删除所有要修改文章的绑定关系
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmNewsMaterial::getNewsId, dto.getId());
            wmNewsMaterialMapper.delete(wrapper);
            wmNews.setCreatedTime(new Date());
            wmNews.setPublishTime(new Date());
            //2.updatebyid
            updateById(wmNews);
        }
        //新增操作
        wmNews.setCreatedTime(new Date());
        wmNews.setPublishTime(new Date());
        save(wmNews);

    }

    /**
     * 从content中解析出来的image的url
     *
     * @param content
     * @return 从content中解析出来的image的url的list集合
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> materials = new ArrayList<>();
        List<Map> maps = JSON.parseArray(content, Map.class);
        for (Map map : maps) {
            if (map.get("type").equals("image")) {
                String imgUrl = (String) map.get("value");
                materials.add(imgUrl);
            }
        }

        return materials;

    }

    /**
     * 绑定文章内容中的图片和文章的关系  type为 0 表示内容引用
     *
     * @param contentImages 图片url的list集合
     * @param id            文章的id
     */
    private void saveRelativeInfoForContent(List<String> contentImages, Integer id) {
        //1.将传来的 contentImages 这些图片的url去其数据库中查到对应的每一个url对的素材的id，封装成一个list
        List<Integer> contentImagesId = new ArrayList<>();
        for (int i = 0; i < contentImages.size(); i++) {
            /*LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmMaterial::getUrl, contentImages.get(i));
            WmMaterial one = wmMaterialService.getOne(wrapper);*/
            Integer imageUrl = getImageId(contentImages.get(i));
            contentImagesId.add(imageUrl);
        }
        //2.将其文章和素材关系进行绑定
        //todo:自定义sql有问题
        /*wmNewsMaterialMapper.saveRelations(contentImagesId, id, (short) 0);*/
        saveRelations(id, contentImages, (short) 0);
    }


    /**
     * 对文章封面的绑定
     *
     * @param dto
     * @param contentImages
     * @param wmNews
     */
    private void saveRelativeInfoForCover(WmNewsDto dto, List<String> contentImages, WmNews wmNews) {
        /*
         * 1.从dto中去获取到type， 0 无图 1 单图 3 多图 null 自动  自动的话就要从content中的contentImages
         * 这个list中去取图做封面,反之，从dto中的images中去取图片
         * */
        if (dto.getType() == null) {
            //自动选封面
            String s = contentImages.get(0);
            wmNews.setType(WemediaConstans.WM_NEWS_TYPE_AUTO);
            wmNews.setImages(s);
            LambdaQueryWrapper<WmNewsMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmNewsMaterial::getMaterialId, getImageId(s));
            WmNewsMaterial one = wmNewsMaterialService.getOne(wrapper);
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            BeanUtils.copyProperties(one, wmNewsMaterial);
            wmNewsMaterial.setType((short) 1);
            wmNewsMaterialService.update(wmNewsMaterial, wrapper);
        }

        if (dto.getType().equals((short) 0) || dto.getImages().size() == 0) {
            //无封面图
            wmNews.setType(WemediaConstans.WM_NEWS_NONE_IMAGE);
        }
        if (dto.getType().equals((short) 1) || dto.getImages().size() == 1) {
            //封面单图
            String imageUrl = dto.getImages().get(0);
            wmNews.setImages(imageUrl);
            Integer imageId = getImageId(imageUrl);
            List<Integer> images = new ArrayList<>();
            images.add(imageId);
            /*wmNewsMaterialMapper.saveRelations(images, wmNews.getId(), (short) 1);*/
            saveRelations(wmNews.getId(), contentImages, (short) 1);
            wmNews.setType(WemediaConstans.WM_NEWS_SINGLE_IMAGE);
        }
        if (dto.getType().equals((short) 3) || dto.getImages().size() >= 2) {
            //多张封面图
            List<Integer> contentImagesId = new ArrayList<>();
            for (int i = 0; i < contentImages.size(); i++) {
            /*LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(WmMaterial::getUrl, contentImages.get(i));
            WmMaterial one = wmMaterialService.getOne(wrapper);*/
                Integer imageUrl = getImageId(contentImages.get(i));
                contentImagesId.add(imageUrl);
            }
            //2.将其文章和素材关系进行绑定
            /*wmNewsMaterialMapper.saveRelations(contentImagesId, wmNews.getId(), (short) 1);*/
            saveRelations(wmNews.getId(), contentImages, (short) 1);
            wmNews.setType(WemediaConstans.WM_NEWS_MANY_IMAGE);

        }


    }

    private Integer getImageId(String url) {
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmMaterial::getUrl, url);
        WmMaterial one = wmMaterialService.getOne(wrapper);
        return one.getId();
    }

    /**
     * 素材和文章的关系保存
     *
     * @param newsId        文章id
     * @param contentImages 图片素材的url的list集合
     * @param type          当前图片与文章的关系 1：封面引用  2：内容引用
     */
    private void saveRelations(Integer newsId, List<String> contentImages, short type) {
        //1.判断list集合中有几张图，多张就循环保存关系到数据库
        WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
        if (contentImages.size() > 1) {
            //多张图
            for (int i = 0; i < contentImages.size(); i++) {
                Integer imageId = getImageId(contentImages.get(i));
                wmNewsMaterial.setNewsId(newsId);
                wmNewsMaterial.setMaterialId(imageId);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
                if (type == 1) {
                    wmNewsMaterial.setType((short) 1);
                } else {
                    wmNewsMaterial.setType((short) 0);
                }
            }
        }
        //单张图
        String imageUrl = contentImages.get(0);
        Integer imageId = getImageId(imageUrl);
        wmNewsMaterial.setNewsId(newsId);
        wmNewsMaterial.setMaterialId(imageId);
        if (type == 1) {
            wmNewsMaterial.setType((short) 1);
        } else {
            wmNewsMaterial.setType((short) 0);
        }
    }


    /**
     * 获取文章详情
     *
     * @param id 文章id
     * @return
     */
    @Override
    public ResponseResult getDetails(Integer id) {
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getId, id);
        try {
            WmNews one = getOne(wrapper);
            return ResponseResult.okResult(one);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteNews(Integer id) {
        //1.对传来的id进行预见性判断
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getId, id);
        WmNews one = getOne(wrapper);
        //2.查数据库看一下文章是否存在
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        //3.根据查的数据，get一下  status 如果为 9则无法删除
        if (one.getStatus().equals(9)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "文章已发布无法删除");
        }

        try {
            removeById(id);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "未知错误");
        }
    }


    /**
     * 文章上下架功能
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult newsDownOrUp(WmNewsDto dto) {
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "id不可缺少3");
        }
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(WmNews::getId, dto.getId());
        WmNews one = getOne(wrapper);
        if (one == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "文章不存在");
        }
        if (!one.getStatus().equals((short) 9)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布状态，不能下架");
        }
        try {
            one.setEnable(dto.getEnable());
            updateById(one);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "未知错误");
        }

    }

}
